Passed
Pull Request — master (#1027)
by
unknown
03:53
created

script.js ➔ download   A

Complexity

Conditions 4

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 10
c 0
b 0
f 0
dl 0
loc 16
rs 9.9
1
var lfm_route = location.origin + location.pathname;
2
var show_list;
3
var sort_type = 'alphabetic';
4
var multi_selection_enabled = false;
5
var selected = [];
6
var items = [];
7
8
$.fn.fab = function (options) {
9
  var menu = this;
10
  menu.addClass('fab-wrapper');
11
12
  var toggler = $('<a>')
13
    .addClass('fab-button fab-toggle')
14
    .append($('<i>').addClass('fas fa-plus'))
15
    .click(function () {
16
      menu.toggleClass('fab-expand');
17
    });
18
19
  menu.append(toggler);
20
21
  options.buttons.forEach(function (button) {
22
    toggler.before(
23
      $('<a>').addClass('fab-button fab-action')
24
        .attr('data-label', button.label)
25
        .attr('id', button.attrs.id)
26
        .append($('<i>').addClass(button.icon))
27
        .click(function () {
28
          menu.removeClass('fab-expand');
29
        })
30
    );
31
  });
32
};
33
34
$(document).ready(function () {
35
  $('#fab').fab({
36
    buttons: [
37
      {
38
        icon: 'fas fa-upload',
39
        label: lang['nav-upload'],
0 ignored issues
show
Bug introduced by
The variable lang seems to be never declared. If this is a global, consider adding a /** global: lang */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
40
        attrs: {id: 'upload'}
41
      },
42
      {
43
        icon: 'fas fa-folder',
44
        label: lang['nav-new'],
45
        attrs: {id: 'add-folder'}
46
      }
47
    ]
48
  });
49
50
  actions.reverse().forEach(function (action) {
0 ignored issues
show
Bug introduced by
The variable actions seems to be never declared. If this is a global, consider adding a /** global: actions */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
51
    $('#nav-buttons > ul').prepend(
52
      $('<li>').addClass('nav-item').append(
53
        $('<a>').addClass('nav-link d-none')
54
          .attr('data-action', action.name)
55
          .attr('data-multiple', action.multiple)
56
          .append($('<i>').addClass('fas fa-fw fa-' + action.icon))
57
          .append($('<span>').text(action.label))
58
      )
59
    );
60
  });
61
62
  sortings.forEach(function (sort) {
0 ignored issues
show
Bug introduced by
The variable sortings seems to be never declared. If this is a global, consider adding a /** global: sortings */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
63
    $('#nav-buttons .dropdown-menu').append(
64
      $('<a>').addClass('dropdown-item').attr('data-sortby', sort.by)
65
        .append($('<i>').addClass('fas fa-fw fa-' + sort.icon))
66
        .append($('<span>').text(sort.label))
67
        .click(function() {
68
          sort_type = sort.by;
69
          loadItems();
70
        })
71
    );
72
  });
73
74
  loadFolders();
75
  performLfmRequest('errors')
76
    .done(function (response) {
77
      JSON.parse(response).forEach(function (message) {
78
        $('#alerts').append(
79
          $('<div>').addClass('alert alert-warning')
80
            .append($('<i>').addClass('fas fa-exclamation-circle'))
81
            .append(' ' + message)
82
        );
83
      });
84
    });
85
86
  $(window).on('dragenter', function(){
87
    $('#uploadModal').modal('show');
88
  });
89
90
  if (usingWysiwygEditor()) {
91
    $('#multi_selection_toggle').hide();
92
  }
93
});
94
95
// ======================
96
// ==  Navbar actions  ==
97
// ======================
98
99
$('#multi_selection_toggle').click(function () {
100
  multi_selection_enabled = !multi_selection_enabled;
101
102
  $('#multi_selection_toggle i')
103
    .toggleClass('fa-times', multi_selection_enabled)
104
    .toggleClass('fa-check-double', !multi_selection_enabled);
105
106
  if (!multi_selection_enabled) {
107
    clearSelected();
108
  }
109
});
110
111
$('#to-previous').click(function () {
112
  var previous_dir = getPreviousDir();
113
  if (previous_dir == '') return;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
114
  goTo(previous_dir);
115
});
116
117
function toggleMobileTree(should_display) {
118
  if (should_display === undefined) {
119
    should_display = !$('#tree').hasClass('in');
120
  }
121
  $('#tree').toggleClass('in', should_display);
122
}
123
124
$('#show_tree').click(function (e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
125
  toggleMobileTree();
126
});
127
128
$('#main').click(function (e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
129
  if ($('#tree').hasClass('in')) {
130
    toggleMobileTree(false);
131
  }
132
});
133
134
$(document).on('click', '#add-folder', function () {
135
  dialog(lang['message-name'], '', createFolder);
0 ignored issues
show
Bug introduced by
The variable lang seems to be never declared. If this is a global, consider adding a /** global: lang */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
136
});
137
138
$(document).on('click', '#upload', function () {
139
  $('#uploadModal').modal('show');
140
});
141
142
$(document).on('click', '[data-display]', function() {
143
  show_list = $(this).data('display');
144
  loadItems();
145
});
146
147
$(document).on('click', '[data-action]', function() {
148
  window[$(this).data('action')]($(this).data('multiple') ? getSelectedItems() : getOneSelectedElement());
149
});
150
151
// ==========================
152
// ==  Multiple Selection  ==
153
// ==========================
154
155
function toggleSelected (e) {
156
  if (!multi_selection_enabled) {
157
    selected = [];
158
  }
159
160
  var sequence = $(e.target).closest('a').data('id');
161
  var element_index = selected.indexOf(sequence);
162
  if (element_index === -1) {
163
    selected.push(sequence);
164
  } else {
165
    selected.splice(element_index, 1);
166
  }
167
168
  updateSelectedStyle();
169
}
170
171
function clearSelected () {
172
  selected = [];
173
174
  multi_selection_enabled = false;
175
176
  updateSelectedStyle();
177
}
178
179
function updateSelectedStyle() {
180
  items.forEach(function (item, index) {
181
    $('[data-id=' + index + ']')
182
      .find('.square')
183
      .toggleClass('selected', selected.indexOf(index) > -1);
184
  });
185
  toggleActions();
186
}
187
188
function getOneSelectedElement(orderOfItem) {
189
  var index = orderOfItem !== undefined ? orderOfItem : selected[0];
190
  return items[index];
191
}
192
193
function getSelectedItems() {
194
  return selected.reduce(function (arr_objects, id) {
195
    arr_objects.push(getOneSelectedElement(id));
196
    return arr_objects
197
  }, []);
198
}
199
200
function toggleActions() {
201
  var one_selected = selected.length === 1;
202
  var many_selected = selected.length >= 1;
203
  var only_image = getSelectedItems()
204
    .filter(function (item) { return !item.is_image; })
205
    .length === 0;
206
  var only_file = getSelectedItems()
207
    .filter(function (item) { return !item.is_file; })
208
    .length === 0;
209
210
  $('[data-action=use]').toggleClass('d-none', !(many_selected && only_file));
211
  $('[data-action=rename]').toggleClass('d-none', !one_selected);
212
  $('[data-action=preview]').toggleClass('d-none', !(many_selected && only_file));
213
  $('[data-action=move]').toggleClass('d-none', !many_selected);
214
  $('[data-action=download]').toggleClass('d-none', !(many_selected && only_file));
215
  $('[data-action=resize]').toggleClass('d-none', !(one_selected && only_image));
216
  $('[data-action=rotate]').toggleClass('d-none', !(one_selected && only_image));
217
  $('[data-action=crop]').toggleClass('d-none', !(one_selected && only_image));
218
  $('[data-action=trash]').toggleClass('d-none', !many_selected);
219
  $('[data-action=open]').toggleClass('d-none', !one_selected || only_file);
220
  $('#multi_selection_toggle').toggleClass('d-none', usingWysiwygEditor() || !many_selected);
221
  $('#actions').toggleClass('d-none', selected.length === 0);
222
  $('#fab').toggleClass('d-none', selected.length !== 0);
223
}
224
225
// ======================
226
// ==  Folder actions  ==
227
// ======================
228
229
$(document).on('click', '#tree a', function (e) {
230
  goTo($(e.target).closest('a').data('path'));
231
  toggleMobileTree(false);
232
});
233
234
function goTo(new_dir) {
235
  $('#working_dir').val(new_dir);
236
  loadItems();
237
}
238
239
function getPreviousDir() {
240
  var working_dir = $('#working_dir').val();
241
  return working_dir.substring(0, working_dir.lastIndexOf('/'));
242
}
243
244
function setOpenFolders() {
245
  $('#tree [data-path]').each(function (index, folder) {
246
    // close folders that are not parent
247
    var should_open = ($('#working_dir').val() + '/').startsWith($(folder).data('path') + '/');
248
    $(folder).children('i')
249
      .toggleClass('fa-folder-open', should_open)
250
      .toggleClass('fa-folder', !should_open);
251
  });
252
253
  $('#tree .nav-item').removeClass('active');
254
  $('#tree [data-path="' + $('#working_dir').val() + '"]').parent('.nav-item').addClass('active');
255
}
256
257
// ====================
258
// ==  Ajax actions  ==
259
// ====================
260
261
function performLfmRequest(url, parameter, type) {
262
  var data = defaultParameters();
263
264
  if (parameter != null) {
0 ignored issues
show
Best Practice introduced by
Comparing parameter to null using the != operator is not safe. Consider using !== instead.
Loading history...
265
    $.each(parameter, function (key, value) {
266
      data[key] = value;
267
    });
268
  }
269
270
  return $.ajax({
271
    type: 'GET',
272
    beforeSend: function(request) {
273
      var token = getUrlParam('token');
274
      if (token !== null) {
275
        request.setRequestHeader("Authorization", 'Bearer ' + token);
276
      }
277
    },
278
    dataType: type || 'text',
279
    url: lfm_route + '/' + url,
280
    data: data,
281
    cache: false
282
  }).fail(function (jqXHR, textStatus, errorThrown) {
0 ignored issues
show
Unused Code introduced by
The parameter textStatus is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter errorThrown is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
283
    displayErrorResponse(jqXHR);
284
  });
285
}
286
287
function displayErrorResponse(jqXHR) {
288
  notify('<div style="max-height:50vh;overflow: scroll;">' + jqXHR.responseText + '</div>');
289
}
290
291
var refreshFoldersAndItems = function (data) {
292
  loadFolders();
293
  if (data != 'OK') {
294
    data = Array.isArray(data) ? data.join('<br/>') : data;
295
    notify(data);
296
  }
297
};
298
299
var hideNavAndShowEditor = function (data) {
300
  $('#nav-buttons > ul').addClass('d-none');
301
  $('#content').html(data);
302
  $('#pagination').removeClass('preserve_actions_space')
303
  clearSelected();
304
}
305
306
function loadFolders() {
307
  performLfmRequest('folders', {}, 'html')
308
    .done(function (data) {
309
      $('#tree').html(data);
310
      loadItems();
311
    });
312
}
313
314
function generatePaginationHTML(el, args) {
315
  var template = '<li class="page-item"><\/li>';
316
  var linkTemplate = '<a class="page-link"><\/a>';
317
  var currentPage = args.currentPage;
318
  var totalPage = args.totalPage;
319
  var rangeStart = args.rangeStart;
320
  var rangeEnd = args.rangeEnd;
321
  var i;
322
323
  // Disable page range, display all the pages
324
  if (args.pageRange === null) {
325
    for (i = 1; i <= totalPage; i++) {
326
      var button = $(template)
327
        .attr('data-num', i)
328
        .append($(linkTemplate).html(i));
329
      if (i == currentPage) {
330
        button.addClass('active');
331
      }
332
      el.append(button);
333
    }
334
335
    return;
336
  }
337
338
  if (rangeStart <= 3) {
339
    for (i = 1; i < rangeStart; i++) {
340
      var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 326. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
341
        .attr('data-num', i)
342
        .append($(linkTemplate).html(i));
343
      if (i == currentPage) {
344
        button.addClass('active');
345
      }
346
      el.append(button);
347
    }
348
  } else {
349
    var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 326. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
350
      .attr('data-num', 1)
351
      .append($(linkTemplate).html(1));
352
    el.append(button);
353
354
    var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 326. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
355
      .addClass('disabled')
356
      .append($(linkTemplate).html('...'));
357
    el.append(button);
358
  }
359
360
  for (i = rangeStart; i <= rangeEnd; i++) {
361
    var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 326. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
362
      .attr('data-num', i)
363
      .append($(linkTemplate).html(i));
364
    if (i == currentPage) {
365
      button.addClass('active');
366
    }
367
    el.append(button);
368
  }
369
370
  if (rangeEnd >= totalPage - 2) {
371
    for (i = rangeEnd + 1; i <= totalPage; i++) {
372
      var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 326. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
373
        .attr('data-num', i)
374
        .append($(linkTemplate).html(i));
375
      el.append(button);
376
    }
377
  } else {
378
    var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 326. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
379
      .addClass('disabled')
380
      .append($(linkTemplate).html('...'));
381
    el.append(button);
382
383
    var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 326. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
384
      .attr('data-num', totalPage)
385
      .append($(linkTemplate).html(totalPage));
386
    el.append(button);
387
  }
388
}
389
390
function createPagination(paginationSetting) {
391
  var el = $('<ul class="pagination" role="navigation"></ul>');
392
393
  var currentPage = paginationSetting.current_page;
394
  var pageRange = 5;
395
  var totalPage = Math.ceil(paginationSetting.total / paginationSetting.per_page);
396
397
  var rangeStart = currentPage - pageRange;
398
  var rangeEnd = currentPage + pageRange;
399
400
  if (rangeEnd > totalPage) {
401
    rangeEnd = totalPage;
402
    rangeStart = totalPage - pageRange * 2;
403
    rangeStart = rangeStart < 1 ? 1 : rangeStart;
404
  }
405
406
  if (rangeStart <= 1) {
407
    rangeStart = 1;
408
    rangeEnd = Math.min(pageRange * 2 + 1, totalPage);
409
  }
410
411
  generatePaginationHTML(el, {
412
    totalPage: totalPage,
413
    currentPage: currentPage,
414
    pageRange: pageRange,
415
    rangeStart: rangeStart,
416
    rangeEnd: rangeEnd
417
  });
418
419
  $('#pagination').append(el);
420
}
421
422
function loadItems(page) {
423
  loading(true);
424
  performLfmRequest('jsonitems', {show_list: show_list, sort_type: sort_type, page: page || 1}, 'html')
425
    .done(function (data) {
426
      selected = [];
427
      var response = JSON.parse(data);
428
      var working_dir = response.working_dir;
429
      items = response.items;
430
      var hasItems = items.length !== 0;
431
      var hasPaginator = !!response.paginator;
432
      $('#empty').toggleClass('d-none', hasItems);
433
      $('#content').html('').removeAttr('class');
434
      $('#pagination').html('').removeAttr('class');
435
436
      if (hasItems) {
437
        $('#content').addClass(response.display);
438
        $('#pagination').addClass('preserve_actions_space');
439
440
        items.forEach(function (item, index) {
441
          var template = $('#item-template').clone()
442
            .removeAttr('id class')
443
            .attr('data-id', index)
444
            .click(toggleSelected)
445
            .dblclick(function (e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
446
              if (item.is_file) {
447
                use(getSelectedItems());
448
              } else {
449
                goTo(item.url);
450
              }
451
            });
452
453
          if (item.thumb_url) {
454
            var image = $('<div>').css('background-image', 'url("' + item.thumb_url + '?timestamp=' + item.time + '")');
455
          } else {
456
            var icon = $('<div>').addClass('ico');
457
            var image = $('<div>').addClass('mime-icon ico-' + item.icon).append(icon);
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable image already seems to be declared on line 454. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
458
          }
459
460
          template.find('.square').append(image);
461
          template.find('.item_name').text(item.name);
462
          template.find('time').text((new Date(item.time * 1000)).toLocaleString());
463
464
          $('#content').append(template);
465
        });
466
      }
467
468
      if (hasPaginator) {
469
        createPagination(response.paginator);
470
471
        $('#pagination a').on('click', function(event) {
472
          event.preventDefault();
473
474
          loadItems($(this).closest('li')[0].getAttribute('data-num'));
475
476
          return false;
477
        });
478
      }
479
480
      $('#nav-buttons > ul').removeClass('d-none');
481
482
      $('#working_dir').val(working_dir);
483
      console.log('Current working_dir : ' + working_dir);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
484
      var breadcrumbs = [];
485
      var validSegments = working_dir.split('/').filter(function (e) { return e; });
486
      validSegments.forEach(function (segment, index) {
487
        if (index === 0) {
488
          // set root folder name as the first breadcrumb
489
          breadcrumbs.push($("[data-path='/" + segment + "']").text());
490
        } else {
491
          breadcrumbs.push(segment);
492
        }
493
      });
494
495
      $('#current_folder').text(breadcrumbs[breadcrumbs.length - 1]);
496
      $('#breadcrumbs > ol').html('');
497
      breadcrumbs.forEach(function (breadcrumb, index) {
498
        var li = $('<li>').addClass('breadcrumb-item').text(breadcrumb);
499
500
        if (index === breadcrumbs.length - 1) {
501
          li.addClass('active').attr('aria-current', 'page');
502
        } else {
503
          li.click(function () {
504
            // go to corresponding path
505
            goTo('/' + validSegments.slice(0, 1 + index).join('/'));
506
          });
507
        }
508
509
        $('#breadcrumbs > ol').append(li);
510
      });
511
512
      var atRootFolder = getPreviousDir() == '';
513
      $('#to-previous').toggleClass('d-none invisible-lg', atRootFolder);
514
      $('#show_tree').toggleClass('d-none', !atRootFolder).toggleClass('d-block', atRootFolder);
515
      setOpenFolders();
516
      loading(false);
517
      toggleActions();
518
    });
519
}
520
521
function loading(show_loading) {
522
  $('#loading').toggleClass('d-none', !show_loading);
523
}
524
525
function createFolder(folder_name) {
526
  performLfmRequest('newfolder', {name: folder_name})
527
    .done(refreshFoldersAndItems);
528
}
529
530
// ==================================
531
// ==         File Actions         ==
532
// ==================================
533
534
function rename(item) {
535
  dialog(lang['message-rename'], item.name, function (new_name) {
0 ignored issues
show
Bug introduced by
The variable lang seems to be never declared. If this is a global, consider adding a /** global: lang */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
536
    performLfmRequest('rename', {
537
      file: item.name,
538
      new_name: new_name
539
    }).done(refreshFoldersAndItems);
540
  });
541
}
542
543
function trash(items) {
544
  notify(lang['message-delete'], function () {
0 ignored issues
show
Bug introduced by
The variable lang seems to be never declared. If this is a global, consider adding a /** global: lang */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
545
    performLfmRequest('delete', {
546
      items: items.map(function (item) { return item.name; })
547
    }).done(refreshFoldersAndItems)
548
  });
549
}
550
551
function crop(item) {
552
  performLfmRequest('crop', {img: item.name})
553
    .done(hideNavAndShowEditor);
554
}
555
556
function rotate(item) {
557
  performLfmRequest('rotate', {img: item.name})
558
    .done(hideNavAndShowEditor);
559
}
560
561
function resize(item) {
562
  performLfmRequest('resize', {img: item.name})
563
    .done(hideNavAndShowEditor);
564
}
565
566
function download(items) {
567
  items.forEach(function (item, index) {
568
    var data = defaultParameters();
569
570
    data['file'] = item.name;
571
572
    var token = getUrlParam('token');
573
    if (token) {
574
      data['token'] = token;
575
    }
576
577
    setTimeout(function () {
578
      location.href = lfm_route + '/download?' + $.param(data);
579
    }, index * 100);
580
  });
581
}
582
583
function open(item) {
584
  goTo(item.url);
585
}
586
587
function preview(items) {
588
  var carousel = $('#carouselTemplate').clone().attr('id', 'previewCarousel').removeClass('d-none');
589
  var imageTemplate = carousel.find('.carousel-item').clone().removeClass('active');
590
  var indicatorTemplate = carousel.find('.carousel-indicators > li').clone().removeClass('active');
591
  carousel.children('.carousel-inner').html('');
592
  carousel.children('.carousel-indicators').html('');
593
  carousel.children('.carousel-indicators,.carousel-control-prev,.carousel-control-next').toggle(items.length > 1);
594
595
  items.forEach(function (item, index) {
596
    var carouselItem = imageTemplate.clone()
597
      .addClass(index === 0 ? 'active' : '');
598
599
    if (item.thumb_url) {
600
      carouselItem.find('.carousel-image').css('background-image', 'url(\'' + item.url + '?timestamp=' + item.time + '\')');
601
    } else {
602
      carouselItem.find('.carousel-image').css('width', '50vh').append($('<div>').addClass('mime-icon ico-' + item.icon));
603
    }
604
605
    carouselItem.find('.carousel-label').attr('target', '_blank').attr('href', item.url)
606
      .append(item.name)
607
      .append($('<i class="fas fa-external-link-alt ml-2"></i>'));
608
609
    carousel.children('.carousel-inner').append(carouselItem);
610
611
    var carouselIndicator = indicatorTemplate.clone()
612
      .addClass(index === 0 ? 'active' : '')
613
      .attr('data-slide-to', index);
614
    carousel.children('.carousel-indicators').append(carouselIndicator);
615
  });
616
617
618
  // carousel swipe control
619
  var touchStartX = null;
620
621
  carousel.on('touchstart', function (event) {
622
    var e = event.originalEvent;
623
    if (e.touches.length == 1) {
0 ignored issues
show
Best Practice introduced by
Comparing e.touches.length to 1 using the == operator is not safe. Consider using === instead.
Loading history...
624
      var touch = e.touches[0];
625
      touchStartX = touch.pageX;
626
    }
627
  }).on('touchmove', function (event) {
628
    var e = event.originalEvent;
629
    if (touchStartX != null) {
0 ignored issues
show
Best Practice introduced by
Comparing touchStartX to null using the != operator is not safe. Consider using !== instead.
Loading history...
630
      var touchCurrentX = e.changedTouches[0].pageX;
631
      if ((touchCurrentX - touchStartX) > 60) {
632
        touchStartX = null;
633
        carousel.carousel('prev');
634
      } else if ((touchStartX - touchCurrentX) > 60) {
635
        touchStartX = null;
636
        carousel.carousel('next');
637
      }
638
    }
639
  }).on('touchend', function () {
640
    touchStartX = null;
641
  });
642
  // end carousel swipe control
643
644
  notify(carousel);
645
}
646
647
function move(items) {
648
  performLfmRequest('move', { items: items.map(function (item) { return item.name; }) })
649
    .done(refreshFoldersAndItems);
650
}
651
652
function getUrlParam(paramName) {
653
  var reParam = new RegExp('(?:[\?&]|&)' + paramName + '=([^&]+)', 'i');
654
  var match = window.location.search.match(reParam);
655
  return ( match && match.length > 1 ) ? match[1] : null;
656
}
657
658
function use(items) {
659
  function useTinymce3(url) {
660
    if (!usingTinymce3()) { return; }
661
662
    var win = tinyMCEPopup.getWindowArg("window");
0 ignored issues
show
Bug introduced by
The variable tinyMCEPopup seems to be never declared. If this is a global, consider adding a /** global: tinyMCEPopup */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
663
    win.document.getElementById(tinyMCEPopup.getWindowArg("input")).value = url;
664
    if (typeof(win.ImageDialog) != "undefined") {
665
      // Update image dimensions
666
      if (win.ImageDialog.getImageData) {
667
        win.ImageDialog.getImageData();
668
      }
669
670
      // Preview if necessary
671
      if (win.ImageDialog.showPreviewImage) {
672
        win.ImageDialog.showPreviewImage(url);
673
      }
674
    }
675
    tinyMCEPopup.close();
676
  }
677
678
  function useTinymce4AndColorbox(url) {
679
    if (!usingTinymce4AndColorbox()) { return; }
680
681
    parent.document.getElementById(getUrlParam('field_name')).value = url;
0 ignored issues
show
Bug introduced by
The variable parent seems to be never declared. If this is a global, consider adding a /** global: parent */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
682
683
    if(typeof parent.tinyMCE !== "undefined") {
684
      parent.tinyMCE.activeEditor.windowManager.close();
685
    }
686
    if(typeof parent.$.fn.colorbox !== "undefined") {
687
      parent.$.fn.colorbox.close();
688
    }
689
  }
690
691
  function useTinymce5(url){
692
    if (!usingTinymce5()) { return; }
693
694
    parent.postMessage({
0 ignored issues
show
Bug introduced by
The variable parent seems to be never declared. If this is a global, consider adding a /** global: parent */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
695
      mceAction: 'insert',
696
      content: url
697
    });
698
699
    parent.postMessage({ mceAction: 'close' });
700
  }
701
702
  function useCkeditor3(url) {
703
    if (!usingCkeditor3()) { return; }
704
705
    if (window.opener) {
706
      // Popup
707
      window.opener.CKEDITOR.tools.callFunction(getUrlParam('CKEditorFuncNum'), url);
708
    } else {
709
      // Modal (in iframe)
710
      parent.CKEDITOR.tools.callFunction(getUrlParam('CKEditorFuncNum'), url);
0 ignored issues
show
Bug introduced by
The variable parent seems to be never declared. If this is a global, consider adding a /** global: parent */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
711
      parent.CKEDITOR.tools.callFunction(getUrlParam('CKEditorCleanUpFuncNum'));
712
    }
713
  }
714
715
  function useFckeditor2(url) {
716
    if (!usingFckeditor2()) { return; }
717
718
    var p = url;
719
    var w = data['Properties']['Width'];
0 ignored issues
show
Bug introduced by
The variable data seems to be never declared. If this is a global, consider adding a /** global: data */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
720
    var h = data['Properties']['Height'];
721
    window.opener.SetUrl(p,w,h);
722
  }
723
724
  var url = items[0].url;
725
  var callback = getUrlParam('callback');
726
  var useFileSucceeded = true;
727
728
  if (usingWysiwygEditor()) {
729
    useTinymce3(url);
730
731
    useTinymce4AndColorbox(url);
732
733
    useTinymce5(url);
734
735
    useCkeditor3(url);
736
737
    useFckeditor2(url);
738
  } else if (callback && window[callback]) {
739
    window[callback](getSelectedItems());
740
  } else if (callback && parent[callback]) {
0 ignored issues
show
Bug introduced by
The variable parent seems to be never declared. If this is a global, consider adding a /** global: parent */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
741
    parent[callback](getSelectedItems());
742
  } else if (window.opener) { // standalone button or other situations
743
    window.opener.SetUrl(getSelectedItems());
744
  } else {
745
    useFileSucceeded = false;
746
  }
747
748
  if (useFileSucceeded) {
749
    if (window.opener) {
750
      window.close();
751
    }
752
  } else {
753
    console.log('window.opener not found');
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
754
    // No editor found, open/download file using browser's default method
755
    window.open(url);
756
  }
757
}
758
//end useFile
759
760
// ==================================
761
// ==     WYSIWYG Editors Check    ==
762
// ==================================
763
764
function usingTinymce3() {
765
  return !!window.tinyMCEPopup;
766
}
767
768
function usingTinymce4AndColorbox() {
769
  return !!getUrlParam('field_name');
770
}
771
772
function usingTinymce5(){
773
    return !!getUrlParam('editor');
774
}
775
776
function usingCkeditor3() {
777
  return !!getUrlParam('CKEditor') || !!getUrlParam('CKEditorCleanUpFuncNum');
778
}
779
780
function usingFckeditor2() {
781
  return window.opener && typeof data != 'undefined' && data['Properties']['Width'] != '';
0 ignored issues
show
Bug introduced by
The variable data seems to be never declared. If this is a global, consider adding a /** global: data */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
782
}
783
784
function usingWysiwygEditor() {
785
  return usingTinymce3() || usingTinymce4AndColorbox() || usingTinymce5() || usingCkeditor3() || usingFckeditor2();
786
}
787
788
// ==================================
789
// ==            Others            ==
790
// ==================================
791
792
function defaultParameters() {
793
  return {
794
    working_dir: $('#working_dir').val(),
795
    type: $('#type').val()
796
  };
797
}
798
799
function notImp() {
800
  notify('Not yet implemented!');
801
}
802
803
function notify(body, callback) {
804
  $('#notify').find('.btn-primary').toggle(callback !== undefined);
805
  $('#notify').find('.btn-primary').unbind().click(callback);
806
  $('#notify').modal('show').find('.modal-body').html(body);
807
}
808
809
function dialog(title, value, callback) {
810
  $('#dialog').find('input').val(value);
811
  $('#dialog').on('shown.bs.modal', function () {
812
    $('#dialog').find('input').focus();
813
  });
814
  $('#dialog').find('.btn-primary').unbind().click(function (e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
815
    callback($('#dialog').find('input').val());
816
  });
817
  $('#dialog').modal('show').find('.modal-title').text(title);
818
}
819